from django.shortcuts import render
from django.views import View
from goods.models import SKU,GoodsCategory
from django.core.paginator import Paginator
from goods.utils import get_breadcrumb
from django import http
from haystack.views import SearchView
# Create your views here.


class ListView(View):
        def get(self,request,category_id):
            # 获取参数:
            page = request.GET.get('page')
            page_size = request.GET.get('page_size')
            ordering = request.GET.get('ordering')

            # 根据 category_id 查询出sku商品
            skus = SKU.objects.filter(category_id=category_id).order_by(ordering)

            category = GoodsCategory.objects.get(id=category_id)

            breadcrumb = get_breadcrumb(category)

            # 分页  per_page 每页的数量
            #paginator(objects_list,per_page=)  objects_list 是模型类查询集
            paginator = Paginator(skus,per_page=page_size)
            # paginator.count

            # page(number): 表示取第几页
            page = paginator.page(page)

            sku_list = []
            for sku in paginator.object_list:
                sku_list.append({
                    'id': sku.id,
                    'default_image_url': sku.default_image_url,
                    'name': sku.name,
                    'price': sku.price

                })

            return http.JsonResponse({
                'code' :0,
                'errmsg' : 'ok',
                'breadcrumb' : breadcrumb,
                'list' : sku_list,
                'count':paginator.num_pages
            })


class HotGoodsView(View):
    def get(self,request,category_id):
        # 根据销量倒叙 从高到低
        skus = SKU.objects.filter(category_id=category_id,is_launched=True).order_by('-sales')[:2]


        hot_skus = []
        for sku in skus:
            hot_skus.append({
                'id': sku.id,
                'default_image_url': sku.default_image_url,
                'price':sku.price
            })

        return http.JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'hot_skus': hot_skus

        })


class MySearchView(SearchView):
    def create_response(self):

        # 获取搜索结果
        data = self.get_context()
        data_list = []
        for result in data['page'].object_list:
            data_list.append({
                'id': result.object.id,
                'name': result.object.name,
                'default_image_url': result.object.default_image_url,
                'price': result.object.price,
                'searchkey': data['query'],
                'page_size': data['paginator'].per_page,
                'count': data['paginator'].count

            })

        return  http.JsonResponse(data_list,safe=False)